package org.misalen.web.server.controllers;

import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.misalen.utils.TextUtil;
import org.misalen.web.database.BaseRepository;
import org.misalen.web.database.util.PaginationFrom;
import org.misalen.web.server.config.ErrorCode;
import org.misalen.web.server.config.FilterForm;
import org.misalen.web.server.config.Uncertain;
import org.misalen.web.server.exception.CustomerException;
import org.misalen.web.server.forms.BasePageForm;
import org.misalen.web.server.util.FormUtil;
import org.misalen.web.service.file.OssFile;
import org.misalen.web.service.pay.alipay.AliPayImpl;
import org.misalen.web.service.pay.wechatpay.WechatPayImpl;
import org.misalen.web.service.push.JPushImpl;
import org.misalen.web.service.sms.AliSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * BaseController
 * 
 * @author guochao
 *
 */
@Component
public class BaseController extends BaseRepository {
	@Autowired
	protected JPushImpl jPushImpl;
	@Autowired
	protected AliSms aliSms;
	@Autowired
	protected OssFile ossFile;
	@Autowired
	protected AliPayImpl aliPay;
	@Autowired
	protected WechatPayImpl wechatPay;

	protected Logger logger;

	public BaseController() {
		logger = Logger.getLogger(getClass());
	}

	@SuppressWarnings("unchecked")
	@ModelAttribute
	public void init(HttpServletRequest request)
			throws CustomerException, IllegalAccessException, InvocationTargetException {
		String url = request.getRequestURI();
		for (String u : Uncertain.notFilter) {
			if (url.indexOf(u) >= 0) {
				return;
			}
		}
		String version = request.getHeader("version");
		if (version != null && version.equals("test")) {
			return;
		}
		if (request.getMethod().equals("GET")) {
			return;
		}
		FilterForm filterForm = new FilterForm();
		BeanUtils.populate(filterForm, request.getParameterMap());
		FormUtil.validate(filterForm);
		String sign = encrypt(filterForm);
		if (!sign.equals(filterForm.getSign())) {
			throw new CustomerException(ErrorCode.SYS_ERROR_CODE_501);
		}

	}

	private static String encrypt(FilterForm filterForm) {
		String imei = filterForm.getImei();
		String macCode = filterForm.getMacCode();
		String uid = filterForm.getUid();
		Long macTime = filterForm.getMacTime();
		String correctKey = TextUtil.MD5(imei + macCode) + TextUtil.MD5(String.valueOf(uid) + String.valueOf(macTime));
		String nonceStr = filterForm.getNonceStr();
		return TextUtil.MD5(correctKey + nonceStr);
	}

	protected static <T> PaginationFrom<T> formToPage(BasePageForm form, Class<T> t) {
		PaginationFrom<T> from = new PaginationFrom<T>();
		from.setAsc(form.getAsc());
		from.setDesc(form.getDesc());
		from.setPage(form.getPage());
		from.setRows(form.getRows());
		return from;
	}

	public String getBaseUrl(HttpServletRequest request) {
		String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath();
		return baseUrl;
	}
	public String getBaseHost(HttpServletRequest request) {
		String baseHost = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
		return baseHost;
	}
	protected static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				if (filename.lastIndexOf('"') > -1) {
					return "." + filename.substring(dot + 1, filename.lastIndexOf('"'));
				}
				return "." + filename.substring(dot + 1);
			}
		}
		return "." + filename;
	}

	public final static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");

			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}
}
